package com.liukaixin.product.ru.data.repositories;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Notice;
import com.liukaixin.product.ru.data.model.Result;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.ResultTypeEnum;
import com.liukaixin.product.ru.service.NoticeService;
import com.liukaixin.product.ru.service.ServiceFactory;
import com.liukaixin.product.ru.util.ACache;
import com.orhanobut.logger.Logger;

import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by Jacob on 2016/9/20.
 */
public class NoticeRepository {

    private static NoticeRepository INSTANCE = null;

    private NoticeService noticeService;

    private NoticeRepository() {
        this.noticeService = ServiceFactory
                .createRetrofitService(NoticeService.class,
                        ServiceFactory.BASE_URL);
    }

    public static NoticeRepository getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new NoticeRepository();
        }
        return INSTANCE;
    }

    public void getNoticeById(final Integer page,
                              final Integer rows,
                              final Integer categoryId,
                              @NonNull
                              final CallBackListener<List<Notice>> callback){
        checkNotNull(callback);

        User user = JSON.parseObject(AppController.getInstance().getCache().getAsString("user"),
                User.class);

        noticeService.getNoticesByUserId(page, rows, categoryId, user.getId())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<Notice>>>() {
                    @Override
                    public void onCompleted() {
                        callback.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());
                        callback.onError(e.getMessage());
                    }

                    @Override
                    public void onNext(Result<List<Notice>> result) {
                        if (result.getCode().equals(ResultTypeEnum.SUCCESS.getValue())) {
                            callback.onNext(result.getBean());
                        } else {
                            callback.onError(result.getMessage());
                        }
                    }
                });
    }

}
